package com.padgett.resourcemanagement.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;
import com.padgett.resourcemanagement.util.DateUtil;

/**
 * Get Business Client including all services and invoices.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxGetAllClientServicesServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxGetAllClientServicesServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String clientId=(String)req.getParameter("clientId");
		if(clientId!=null){
			String filterCompleted=req.getParameter("FilterCompleted");
			String filterIncomplete=req.getParameter("FilterIncomplete");
			String filterBillable=req.getParameter("FilterBillable");
			String filterNonBillable=req.getParameter("FilterNonBillable");
			boolean completed=(filterCompleted!=null?true:false);
			boolean incomplete=(filterIncomplete!=null?true:false);
			boolean billable=(filterBillable!=null?true:false);
			boolean nonBillable=(filterNonBillable!=null?true:false);
			Key key=new KeyFactory.Builder(KeyFactory.stringToKey(clientId)).getKey();
			List<Entity> entities=ClientDAO.getAllClientServices(key,completed,incomplete,billable,nonBillable);
			JSONObject response=new JSONObject();
			String errorResponse=null;
			try {
				response.put("success",true);
				response.put("size",entities.size());
				List<JSONObject> services=new ArrayList<JSONObject>();
				Iterator<Entry<String, Object>> iterator=null;
				for(Entity entity:entities){
					JSONObject service=new JSONObject();
					service.put("serviceId", KeyFactory.keyToString(entity.getKey()));
					iterator=entity.getProperties().entrySet().iterator();
					while(iterator.hasNext()){
						Map.Entry<String, Object> entry=(Map.Entry<String, Object>)iterator.next();
						String entryKey=entry.getKey();
						if(entry.getValue() instanceof Date){
							service.put(entry.getKey(), DateUtil.formatDate(((Date)entry.getValue()), DateUtil.LONG_DATE_FORMAT));
						}else if(entry.getValue() instanceof Text){
							service.put(entry.getKey(), ((Text)entry.getValue()).toString());
						}else{
							service.put(entry.getKey(), entry.getValue());
						}
						if(entryKey.equalsIgnoreCase("accountant")&&entry.getValue()!=null){
							// Get Accountant nickname
							Key accountantKey=new KeyFactory.Builder("User",(String)entry.getValue()).getKey();
							Entity accountant=ClientDAO.loadEntity(accountantKey);
							if(accountant!=null){
								service.put("AccountantName",accountant.getProperty("Nickname"));
							}
						}
					}
					services.add(service);
				}
				response.put("data", services);
			} catch (JSONException e) {
				logger.severe(e.getMessage());
				e.printStackTrace();
				errorResponse="{\"success\":false,\"error\":\""+e.getMessage()+"\"}";
			}
			if(errorResponse!=null){
				resp.getWriter().write(errorResponse);
			}else{
				resp.getWriter().write(response.toString());
			}
		}else{
			String response="{\"success\":false,\"error\":\"Invalid Client\"}";
			resp.getWriter().write(response.toString());
		}
	}
}
